/***
* description:中间表子表，处理ＰＤＡ上传上来的数据
* modify history:
* 1、Fuhaisha  2011-5-25   添加活动订单逻辑
* 2、Huangxiaojiang  2011-6-23   添加经销商订单逻辑
*/
trigger CreateOderItemInventoryCompetitor on VisitAndOrderDetailsInProcess__c (after insert) 
{
    if(trigger.isInsert)
    {   
        //用于蓝色风暴和竞品活动的变量
        integer iBaozhu=0;
        integer iDuitou=0;
        integer iDuanjia=0;       
       
        List<Order_Item__c> orderItemList = new List<Order_Item__c>();
        List<ID> OList = new List<ID>();
        List<Competitor__c> competitorList = new List<Competitor__c>();
        List<Inventory__c> InvList = new List<Inventory__c>();
        Set<ID> InStoreVisitId = new Set<ID>();
        
        list<recordtype> rlist=new list<recordtype>();
        id returnorder;
        id freegoods;
        id normal;
        id activityOrder;
        id shipmentOrder;
        id distributorReturnOrder;        
        
        rlist=[select id,DeveloperName from recordtype where sobjecttype=:'Order_Item__c' and 
                ( DeveloperName=:'free_goods' or DeveloperName=:'normal' or DeveloperName=:'Return' or DeveloperName=:'ActivityOrder')];
        
        for(recordtype rt:rlist){                            //匹配recordtypeid
            if(rt.DeveloperName=='free_goods'){
                freegoods=rt.id;
            }else if(rt.DeveloperName=='normal'){
                normal=rt.id;
            }else if(rt.DeveloperName=='Return'){
                returnorder=rt.id;
            }
            else if(rt.DeveloperName=='ActivityOrder')
            {
                activityOrder=rt.id;
            }else if(rt.DeveloperName=='ShipmentOrder'){//add by xiaojiang 6-23
                shipmentOrder=rt.id;
            }else if(rt.DeveloperName=='DistributorReturnOrder'){
             distributorReturnOrder=rt.id;
            }
        } 
        //保存资源数
        map<string,Integer> resourceList=new map<string,Integer>();       
        for(VisitAndOrderDetailsInProcess__c vis : Trigger.new){
            if(vis.Type__c == 'OrderItem')
            {
                Order_Item__c ordItem = new Order_Item__c();
                ordItem.RealItemNumber__c = vis.RealItemNumber__c;
                ordItem.RealPackage__c = vis.RealPackage__c;
                ordItem.Return_Reason__c = vis.ReturnReason__c;
                ordItem.ReturnReasonList__c = vis.ReturnReasonList__c;   
                ordItem.Package__c = vis.Package__c;
                ordItem.Order_Name__c = (ID)vis.Order__c;
                ordItem.Product_Name__c = vis.Product__c;
                ordItem.OrderNumber__c = vis.OrderNumber__c;
                ordItem.Price_after_tax__c = vis.Product_Value__c;
                ordItem.Value__c = ordItem.Price_after_tax__c * ordItem.OrderNumber__c; 
                ordItem.ValueOfExfactoryPricePretax__c = vis.ExfactoryPricePretax__c * vis.OrderNumber__c;
                ordItem.Resource_Allocation_Detail__c=vis.Resource_Allocation_Detail__c;  
                ordItem.Order_Type__c=vis.OrderType__c;
                if(vis.Resource_Allocation_Detail__c!=NULL)
                    resourceList.put(vis.Resource_Allocation_Detail__c,Integer.valueOf(vis.OrderNumber__c));
                
                if(vis.OrderType__c=='常规'){
                    ordItem.recordtypeid=normal;
                }else if(vis.OrderType__c=='退货'){
                    ordItem.recordtypeid=returnorder;
                }else if(vis.OrderType__c=='免费产品'){
                    ordItem.recordtypeid=freegoods;
                } else if(vis.OrderType__c=='活动订单')
                     ordItem.recordtypeid=activityOrder;
                //add by xiaojiang 6-23
                else if(vis.ordertype__c=='经销商订单'){
                     //ordItem.TSRApproval__c=true;
                     //ordItem.TSRChecker__c=userInfo.getUserId();
                     ordItem.RecordTypeId=shipmentOrder;
                     //计算折前金额小计
                     if(vis.Package__c.contains('箱')){
                         ordItem.Value__c = vis.Suggested_Retail_Price__c * vis.OrderNumber__c;
                         ordItem.UnitPrice__c=vis.Suggested_Retail_Price__c;
                     }else{
                         if(vis.Package__c.contains('罐')||vis.Package__c.contains('盒')){
                             ordItem.Value__c = vis.SuggestedRetailPriceTinBox__c * vis.OrderNumber__c;
                             ordItem.UnitPrice__c=vis.SuggestedRetailPriceTinBox__c;
                         }    
                     }
                     //税后金额小计
                     ordItem.AmountAfterTax__c=vis.ExfactoryPriceAfterTax__c*vis.OrderNumber__c;
                     //税前金额小计
                     ordItem.AmountPreTax__c=vis.ExfactoryPricePretax__c*vis.OrderNumber__c;
                     //保质期
                     ordItem.GuaranteePeriod__c=vis.Guarantee_Period__c;
                 }
                else if(vis.ordertype__c=='经销商退订'){
                    ordItem.RecordTypeId=distributorReturnOrder; 
                    ordItem.ExpiredDate__c=vis.ExpiredDate__c;
                    //保质期
                    ordItem.GuaranteePeriod__c=vis.Guarantee_Period__c;            
                }
                
                                 
                /*modify by xiaojiang 101011*/
                 if(vis.Parent__c!=null)
                 {
                 orderItemList.add(ordItem);
                 }
                 /*end modify*/
                /*orderItemList.add(ordItem);*/
                if(vis.DetailStatus__c == 'End'){
                    OList.add((ID)vis.Order__c);
                }
            }
            else if(vis.Type__c == 'Competitor')
            {
                Competitor__c competitor = new Competitor__c();
                competitor.Displan__c = vis.CompetitorDisplay__c;
                competitor.in_store_visit__c = (ID)vis.In_Store_Visit__c;
                competitor.Brand__c = vis.CompetitorBrand__c;
                
                //增加蓝色风暴及竞品促销活动信息 by xiaojiang 20110414
                if(vis.BlueStormBaoZhu__c!=null){//处理包柱
                    iBaozhu=integer.valueOf(vis.BlueStormBaoZhu__c);
                    competitor.BlueStormBaoZhuI__c=iBaozhu;
                    if(iBaozhu<3&&iBaozhu>0){
                        competitor.BlueStormBaoZhu__c=string.valueOf(iBaozhu)+'个包柱门店';    
                    }else{
                        if(iBaozhu>=3){
                             competitor.BlueStormBaoZhu__c='3个及以上包柱门店';
                        }
                    }                    
                }
                if(vis.BlueStormDuiTou__c!=null){//处理堆头
                    iDuitou=integer.valueOf(vis.BlueStormDuiTou__c);
                    competitor.BlueStormDuiTouI__c=iDuitou;
                    if(iDuitou<3&&iDuitou>0){
                        competitor.BlueStormDuiTou__c=string.valueOf(iDuitou)+'个堆头门店';    
                    }else{
                        if(iDuitou>=3){
                             competitor.BlueStormDuiTou__c='3个及以上堆头门店';
                        }
                    }                    
                }
                if(vis.BlueStormDuanJia__c!=null){//处理端架
                    iDuanjia=integer.valueOf(vis.BlueStormDuanJia__c);
                    competitor.BlueStormDuanJiaI__c=iDuanjia; 
                    if(iDuanjia<3&&iDuanjia>0){
                        competitor.BlueStormDuanJia__c=string.valueOf(iDuanjia)+'个端架门店';    
                    }else{
                        if(iDuanjia>=3){
                             competitor.BlueStormDuanJia__c='3个及以上端架门店';
                        }
                    }                    
                }                             

                //赋值竞品促销活动
                competitor.PromotionActivities__c=vis.PromotionActivities__c;                
                
                /*modify by xiaojiang 101011*/
                if(vis.Parent__c!=null)
                 {
                  competitorList.add(competitor);
                 }
                /*end modify*/
                /*competitorList.add(competitor);*/
            }
            else if(vis.Type__c == 'Inventory')
            {
                Inventory__c inv = new Inventory__c();
                inv.GreaterThan6Months__c = vis.GreaterThan6Months__c;
                inv.GreaterThan7Months__c = vis.GreaterThan7Months__c;
                inv.GreaterThan9Months__c = vis.GreaterThan9Months__c;
                inv.Inventory__c = vis.Inventory__c;
                inv.Display__c = vis.MJNDisplay__c;
                inv.Product_Name__c = vis.Product__c;
                inv.Retail_Price__c = vis.RetailPrice__c;
                inv.In_Store_Visit__c = (ID)vis.In_Store_Visit__c;
                InStoreVisitId.add(vis.In_Store_Visit__c);
                 /*modify by xiaojiang 101011*/
                if(vis.Parent__c!=null)
                 {
                  InvList.add(inv);  
                 }
                /*end modify*/
                /*InvList.add(inv);*/                                                                                
            }
        }
        
        if(orderItemList.size() > 0)
        {
            insert orderItemList; // fix
        }
            
        if(OList.size() > 0){
            List<Order__c> UOrderList = new List<Order__c>();
            List<Order__c> OrderList = new List<Order__c>();  
            OrderList = [Select id,ItemsDone__c From Order__c where id in: OList];
            for(Order__c o : OrderList )
            {
                o.ItemsDone__c = true;
                UOrderList.add(o);
            }
            update UOrderList;
        }
        
        //更改Activity Management相应的已使用资数
        List<Resource_Allocation_Detail__c> updateResourceList=new List<Resource_Allocation_Detail__c>();
        if(resourceList.size()>0)
        {
            List<Resource_Allocation_Detail__c> radList=[select id,HasUsedResourceNumber__c from Resource_Allocation_Detail__c 
                                                                                  where id in:resourceList.keySet()];
            for(Resource_Allocation_Detail__c rad:radList)   
            {
                Integer num=0;
                if(resourceList.get(rad.Id)!=NULL)
                    num=resourceList.get(rad.Id);
                    
                    rad.HasUsedResourceNumber__c+=num;
               updateResourceList.add(rad);
            }
        }
        update updateResourceList;
        
        if(competitorList.size() > 0)
        {
            insert competitorList;
        }
        if(InvList.size() > 0)
        {
            List<Inventory__c> InvList_part1 = new List<Inventory__c>();
            List<Inventory__c> InvList_part2 = new List<Inventory__c>();
            if(InvList.size() > 100)
            {
                for(integer num = 0; num < InvList.size()/2; num++)
                {
                    InvList_part1.add(InvList.get(num));
                }
                for(integer num = InvList.size()/2; num < InvList.size(); num++)
                {
                    InvList_part2.add(InvList.get(num));
                }
                insert InvList_part1;
                insert InvList_part2;                
            }
            else{
                insert InvList;
            }
            TriggerDateISV.invokeByTrigger(InStoreVisitId); 
        }
    }
}